/**
 * Copyright (C) 2013 DaiKit.com - daikit4gxt module (admin@daikit.com)
 *
 *         Project home : http://code.daikit.com/daikit4gxt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.daikit.daikit4gxt.client.action.base;

import com.daikit.commons.shared.utils.DkIdGenerator;
import com.daikit.daikit4gxt.client.DkBaseMain;
import com.daikit.daikit4gxt.client.DkBaseMainController;
import com.daikit.daikit4gxt.client.action.DkBaseAction;
import com.daikit.daikit4gxt.client.action.DkChainActionCreator;
import com.daikit.daikit4gxt.client.log.DkLogger;
import com.daikit.daikit4gxt.client.screen.DkBaseScreen;


/**
 * Show Screen action. Called by {@link DkBaseMainController#showScreen(Class, Object...)}
 * 
 * @author tcaselli
 * @version $Revision$ Last modifier: $Author$ Last commit: $Date$
 */
public class DkBaseShowScreenAction
{

	protected static DkLogger log = DkLogger.getLog(DkBaseShowScreenAction.class);

	/**
	 * Show Screen action. Called by {@link DkBaseMainController#showScreen(Class, Object...)} after
	 * {@link DkBaseInitlializeCurrentScreenAction}
	 * 
	 * @param clazz
	 *           the screen class
	 * @param optionalArgs
	 *           optional arguments
	 * @return a new instance of the show screen action.
	 */
	public static DkBaseAction<Void> get(final Class<? extends DkBaseScreen> clazz, final Object... optionalArgs)
	{
		final DkBaseAction<Void> actionShowScreen = new DkBaseAction<Void>(DkBaseMain.i18n().action_showScreen_loadingLabel())
		{
			// to prevent onBeforeScreenLeft(this) to be called many times. (for
			// example if a pop-up asking to save is displayed and response is "NO")
			private boolean firstCall = true;

			@Override
			protected void run()
			{
				final DkBaseScreen currentScreen = DkBaseMain.controller().getCurrentScreen();
				// if there is no screen displayed or if the screen to display is not the same than the current screen.
				if (currentScreen == null || !currentScreen.getClass().getName().equals(clazz.getName()))
				{
					if (firstCall && !DkBaseMain.controller().onBeforeScreenLeft(this))
					{
						DkBaseShowScreenAction.log.debug("[BaseShowScreenAction Screen {"
								+ (currentScreen == null ? "null" : currentScreen.getClass().getName()) + "} can't be left.]");
						firstCall = false;
						this.stopChain();
					}
					else
					{
						// there we verify that the screen to show is not already created and stored in the
						// MainController screens map. If it is not , a new one is created.
						final DkBaseScreen toShow = DkBaseMain.controller().getScreenInstance(clazz);
						if (currentScreen == null || DkBaseMain.controller().getGui().removeCurrentScreenFromContainer())
						{
							DkBaseMain.controller().setCurrentScreen(null);
							if (currentScreen != null)
							{
								DkBaseShowScreenAction.log.debug("[BaseShowScreenAction Screen {" + currentScreen.getClass().getName()
										+ "} Closed]");
							}
							DkBaseMain.controller().getGui().addScreenToContainer(toShow);
							DkBaseMain.controller().setPreviousScreen(currentScreen);
							DkBaseMain.controller().setCurrentScreen(toShow);
							DkBaseMain.controller().setScreenDisplayId(DkIdGenerator.generateRandomId(10));
							DkBaseMain.controller().onScreenBeforeShow(currentScreen, optionalArgs);
							DkBaseMain.controller().getGui().forceLayoutOnScreen();
							DkBaseShowScreenAction.log.debug("[BaseShowScreenAction Screen {" + toShow.getClass().getName()
									+ "} Displayed (layout forced)]");
						}
						else
						{
							DkBaseShowScreenAction.log.warn("[BaseShowScreenAction Screen {" + clazz.getName() + "} NOT Removable]");
						}
					}
					onSuccess();
				}
				else
				{
					stopChain(); // TODO : throw exception here that can be caught and processed.
					onSuccess();
				}
			}
		};
		if (DkBaseMain.controller().getCurrentScreen() == null
				|| !clazz.getName().equals(DkBaseMain.controller().getCurrentScreen().getClass().getName()))
		{
			actionShowScreen.setLastChainActionCreator(new DkChainActionCreator()
			{
				@Override
				public DkBaseAction<?> getCreatedActions()
				{
					final DkBaseAction<?> actionInitializeScreen = DkBaseInitlializeCurrentScreenAction.get(optionalArgs);
					final DkBaseAction<?> actionReloadScreen = DkBaseReloadCurrentScreenAction.get(false, optionalArgs);
					final DkBaseAction<?> ret = actionInitializeScreen != null ? actionInitializeScreen : actionReloadScreen;
					if (actionInitializeScreen != null)
					{
						ret.setLastChainAction(actionReloadScreen);
					}
					return ret;
				}
			});
		}
		return actionShowScreen;
	}
}
